<template>
  <div>
    <!-- 导航栏 -->
    <van-nav-bar
      title="入驻申请"
      left-arrow
      :border="false"
      fixed
      @click-left="$utils.back($route.path);"
    />
    <div class="has-top" />

    <div class="register-form">
      <van-cell-group>
        <van-cell class="flex-v-c" title="门店Logo" required>
          <van-uploader
            slot="right-icon"
            v-model="avar"
            class="avar"
            :max-count="1"
            :after-read="(file)=>{afterRead(file,'logo')}"
            preview-size="1.6rem"
            @delete="(file,detail)=>{afterDelete(file,detail,'logo')}"
          />
        </van-cell>
        <van-field
          v-model="model.storeName.value"
          required
          clearable
          :label="model.storeName.label"
          placeholder="请填写门店名称"
        />
        <van-cell class="flex-v-c" title="广告轮播图" required />
        <van-cell class="ptb-20 plr-30">
          <van-uploader
            slot="title"
            v-model="advertPictures"
            class="advertPictures"
            multiple
            :max-count="10"
            :after-read="(file)=>{afterRead(file,'advertPictures')}"
            preview-size="2rem"
            @delete="(file,detail)=>{afterDelete(file,detail,'advertPictures')}"
          />
        </van-cell>
        <van-field
          v-model="model.storeExplain.value"
          clearable
          :label="model.storeExplain.label"
          placeholder="请填写店铺说明"
        />
        <van-field
          v-model="model.phone.value"
          type="tel"
          required
          clearable
          :label="model.phone.label"
          placeholder="请填写门店电话"
        />
        <van-field
          v-model="model.concactName.value"
          required
          clearable
          :label="model.concactName.label"
          placeholder="请填写联系人姓名"
        />
        <van-field
          v-model="model.area.value"
          readonly
          required
          clickable
          :label="model.area.label"
          placeholder="选择门店城市"
          @click="showArea = true"
        />
        <van-field
          v-model="model.address.value"
          type="textarea"
          clearable
          :label="model.address.label"
          placeholder="请输入详细地址"
          rows="1"
          autosize
        >
          <van-icon
            slot="right-icon"
            name="location"
            :color="model.address.value.length > 0?'#f44':''"
            @click="showAmap = true"
          />
        </van-field>
        <van-field
          v-model="model.addressDesc.value"
          type="textarea"
          clearable
          :label="model.addressDesc.label"
          placeholder="请输入地址说明"
          rows="1"
          autosize
        />
        <van-field
          v-model="model.startTime.value"
          readonly
          clickable
          required
          clearable
          :label="model.startTime.label"
          placeholder="选择开始营业时间"
          @click="startTime = true"
        />
        <van-field
          v-model="model.endTime.value"
          readonly
          clickable
          required
          clearable
          :label="model.endTime.label"
          placeholder="选择结束营业时间"
          @click="endTime = true"
        />
        <van-field
          v-model="model.bussinessType.value"
          readonly
          clickable
          required
          :label="model.bussinessType.label"
          placeholder="请选择商户类型"
          @click="showBussinessType = true"
        />
        <van-popup v-model="showBussinessType" position="bottom">
          <van-picker
            item-height="45"
            visible-item-count="4"
            show-toolbar
            :columns="sortList"
            @cancel="showBussinessType = false"
            @confirm="onConfirm"
          />
        </van-popup>
        <van-cell class="flex-v-c" title="门店环境" required />
        <van-cell class="ptb-20 plr-30">
          <van-uploader
            slot="title"
            v-model="shopPictures"
            class="advertPictures"
            multiple
            :after-read="(file)=>{afterRead(file,'shopPictures')}"
            preview-size="2rem"
            @delete="(file,detail)=>{afterDelete(file,detail,'shopPictures')}"
          />
        </van-cell>
        <van-field
          v-model="model.description.value"
          type="textarea"
          :label="model.description.label"
          placeholder="请输入门店介绍"
          rows="1"
          autosize
          clearable
        />
        <van-field
          v-model="model.referrer.value"
          :label="model.referrer.label"
          placeholder="请输入推荐码"
          clearable
        />
        <van-field
          v-model="model.code.value"
          required
          center
          clearable
          :label="model.code.label"
          placeholder="请输入右图验证码"
        >
          <!--验证码组件-->
          <s-identify
            slot="button"
            :identify-code="identify.identifyCode"
            @refreshCode="refreshCode"
          />
        </van-field>
      </van-cell-group>
      <div class="mtb-30 plr-20">
        <van-button type="danger" size="large" @click="submit">提交申请</van-button>
      </div>

      <!-- 营业时间选择 -->
      <van-popup v-model="startTime" position="bottom">
        <van-datetime-picker
          item-height="45"
          visible-item-count="4"
          type="time"
          title="开始营业时间"
          @confirm="(val)=>{TimeSelect(val,'start')}"
          @cancel="startTime = false"
        />
      </van-popup>
      <van-popup v-model="endTime" position="bottom">
        <van-datetime-picker
          item-height="45"
          visible-item-count="4"
          type="time"
          title="结束营业时间"
          @confirm="(val)=>{TimeSelect(val,'end')}"
          @cancel="endTime = false"
        />
      </van-popup>

      <!-- 城市选择 -->
      <van-popup v-model="showArea" position="bottom">
        <van-area :area-list="areaList" @confirm="areaSelect" @cancel="showArea = false" />
      </van-popup>
    </div>

    <!-- 地图选择地址 -->
    <transition name="van-slide-right">
      <amap-select
        v-show="showAmap"
        :init-amap="initAmap"
        :data-model="model"
        :client-width="clientWidth"
        @closeAmap="showAmap=false"
        @confirmAmap="confirmAmap"
      />
    </transition>
  </div>
</template>

<script>
import SIdentify from 'components/sIdentify'
import amapSelect from 'components/amapSelect'
import areaList from 'utils/area'
import { upLoad } from 'api/upload'
import { getStoreCategoryTreeList } from 'api/storeCategory'
import { storeApply } from 'api/store'

export default {
  components: {
    SIdentify,
    amapSelect
  },
  props: {
    clientWidth: {
      type: Number,
      default: document.body.clientWidth
    }
  },
  data() {
    return {
      avar: [],
      advertPictures: [],
      shopPictures: [],
      model: {
        logo: {
          label: '门店Logo',
          value: '',
          require: true,
          requireMessage: '请上传门店Logo'
        },
        storeName: {
          label: '门店名称',
          value: '',
          require: true,
          requireMessage: '请输入门店名称'
        },
        advertPictures: {
          label: '轮播广告',
          value: [],
          minLength: 1,
          minLengthMessage: '请至少上传一张广告轮播图'
        },
        storeExplain: {
          label: '店铺说明',
          value: ''
        },
        phone: {
          label: '门店电话',
          value: '',
          require: true,
          requireMessage: '请输入门店电话'
        },
        concactName: {
          label: '联系人',
          value: '',
          require: true,
          requireMessage: '请输入联系人姓名'
        },
        area: {
          label: '门店城市',
          value: '',
          ProvinceId: 0,
          ProvinceName: '',
          CityId: 0,
          CityName: '',
          AreaId: 0,
          AreaName: '',
          require: true,
          requireMessage: '请选择城市'
        },
        address: {
          label: '详细地址',
          value: ''
        },
        Lng: {
          label: '经度',
          value: 0
        },
        Lat: {
          label: '纬度',
          value: 0
        },
        addressDesc: {
          label: '地址说明',
          value: ''
        },
        startTime: {
          label: '开始营业',
          value: '',
          require: true,
          requireMessage: '请选择开始营业时间'
        },
        endTime: {
          label: '结束营业',
          value: '',
          require: true,
          requireMessage: '请选择结束营业时间'
        },
        bussinessType: {
          label: '商户类型',
          value: '',
          id: 0,
          require: true,
          requireMessage: '请选择商户类型'
        },
        shopPictures: {
          label: '门店环境',
          value: [],
          minLength: 1,
          minLengthMessage: '请至少上传一张店铺环境图'
        },
        description: {
          label: '门店介绍',
          value: ''
        },
        referrer: {
          label: '推荐码',
          value: ''
        },
        code: {
          label: '验证码',
          value: '',
          require: true,
          requireMessage: '请输入验证码'
        }
      },
      startTime: false,
      endTime: false,
      showArea: false,
      areaList: areaList,
      showAmap: false,
      initAmap: false,
      showBussinessType: false,
      sortList: [],
      identify: {
        // 随机产生验证码的字符串
        identifyCodes: '1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ',
        identifyCode: ''
      }
    }
  },
  created() {
    // 获取商户分类
    this.getStoreCategoryTreeList()
    // 初始化验证码
    this.refreshCode()
  },
  mounted() {
    this.initAmap = true
  },
  methods: {
    afterRead(file, type) {
      // console.log(file);
      if (file.length) {
        for (let i = 0, len = file.length; i < len; i++) {
          upLoad({
            Content: this.$utils.getCaption(file[i].content, 'base64,'),
            FileType: this.$utils.getCaption(file[i].file.type, '/')
          }).then(res => {
            // console.log(res);
            if (res) {
              if (type == 'logo') {
                this.model.logo.value = res.Data.Path
              } else if (type == 'advertPictures') {
                this.model.advertPictures.value.push(res.Data.Path)
              } else if (type == 'shopPictures') {
                this.model.shopPictures.value.push(res.Data.Path)
              }
            }
          })
        }
      } else {
        upLoad({
          Content: this.$utils.getCaption(file.content, 'base64,'),
          FileType: this.$utils.getCaption(file.file.type, '/')
        }).then(res => {
          // console.log(res);
          if (res) {
            if (type === 'logo') {
              this.model.logo.value = res.Data.Path
            } else if (type === 'advertPictures') {
              this.model.advertPictures.value.push(res.Data.Path)
            } else if (type === 'shopPictures') {
              this.model.shopPictures.value.push(res.Data.Path)
            }
          }
        })
      }
    },
    afterDelete(file, detail, type) {
      if (type == 'logo') {
        this.model.logo.value = ''
      } else if (type == 'advertPictures') {
        this.model.advertPictures.value.splice(detail.index, 1)
      } else if (type == 'shopPictures') {
        this.model.shopPictures.value.splice(detail.index, 1)
      }
    },
    // 验证码部分start
    randomNum(min, max) {
      return Math.floor(Math.random() * (max - min) + min)
    },
    refreshCode() {
      this.identify.identifyCode = ''
      this.makeCode(this.identify.identifyCodes, 4)
    },
    makeCode(o, l) {
      for (let i = 0; i < l; i++) {
        this.identify.identifyCode += this.identify.identifyCodes[this.randomNum(0, this.identify.identifyCodes.length)]
      }
    },
    // 验证码部分end
    // 保存地图详细地址
    confirmAmap(dataModel) {
      // console.log(this.model);
    },
    onConfirm(item) {
      this.model.bussinessType.value = item.text
      this.model.bussinessType.id = item.value
      this.showBussinessType = false
    },
    // 营业时间选择
    TimeSelect(item, type) {
      if (type == 'start') {
        this.model.startTime.value = item
        this.startTime = false
      } else {
        this.model.endTime.value = item
        this.endTime = false
      }
    },
    // 商区选择
    areaSelect(item) {
      // console.log(item);
      if (item[2].code) {
        this.model.area.value = item[0].name + '-' + item[1].name + '-' + item[2].name
      } else {
        this.model.area.value = item[0].name + '-' + item[1].name
      }
      this.model.area.ProvinceName = item[0].name
      this.model.area.ProvinceId = item[0].code
      this.model.area.CityName = item[1].name
      this.model.area.CityId = item[1].code
      this.model.area.AreaName = item[2].name
      this.model.area.AreaId = item[2].code
      this.showArea = false
    },
    getStoreCategoryTreeList() {
      getStoreCategoryTreeList(0).then(res => {
        // console.log(res);
        if (res) {
          for (let i = 0, len = res.Data.length; i < len; i++) {
            this.sortList.push({
              text: res.Data[i].CategoryName,
              value: res.Data[i].Id
            })
          }
        }
      })
    },
    submit() {
      const self = this
      // 表单验证
      if (self.$utils.formValidate(self.model).valid) {
        // 验证通过
        const code = self.model.code.value.toLowerCase()
        const input = self.identify.identifyCode.toLowerCase()
        if (code === input) {
          storeApply(parseInt(this.$route.query.userId), self.model).then(res => {
            if (res) {
              this.$toast({
                type: 'success',
                message: '已提交申请审核',
                forbidClick: true,
                onClose: function() {
                  self.$router.back()
                }
              })
            }
          })
        } else {
          this.$toast('验证码输入不正确')
          self.refreshCode()
        }
      } else {
        this.$toast(self.$utils.formValidate(self.model).msg)
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.van-uploader {
  /deep/ .van-uploader__upload,
  /deep/ .van-uploader__preview {
    margin: 0;
  }
}
.advertPictures {
  /deep/ .van-uploader__upload,
  /deep/ .van-uploader__preview {
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>
